/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uk.ac.cam.ccn.sac.modules.audio;

import uk.ac.cam.ccn.sac.modules.audio.AudioThread;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;

/**
 *
 * @author Thomas
 */
public class CaptureThread extends AudioThread{
    public boolean isRecording=true;
    private TargetDataLine line = null;
    private OutputStream out = null;
    
    public CaptureThread(){
        super("CaptureThread");
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
        try{
            line = (TargetDataLine)AudioSystem.getLine(info);
            out = new ByteArrayOutputStream();
        }catch(Exception e){
            System.out.println("Cannot acquire line");
            if(line!=null)
                line.close();
        }
    }
    
    public CaptureThread(OutputStream stream){
        super("CaptureThread (stream)");
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
        try{
            line = (TargetDataLine)AudioSystem.getLine(info);
            out = stream;
        }catch(Exception e){
            System.out.println("Cannot acquire line");
            if(line!=null)
                line.close();
        }
    }
    
    @Override
    public void run(){
        int bufferSize = (int)format.getSampleRate() * format.getFrameSize();
        byte buffer[] = new byte[bufferSize];
        
        try{
            line.open(format);
            line.start();
            do{
                int count = line.read(buffer, 0, buffer.length);
                // if we read something we write it in the buffer
                if(count > 0){
                    out.write(buffer, 0, count);
                    out.flush();
                }
            }while(isRecording);            
        }catch(Exception e){
                System.out.println("Error while recording");
        }finally{
            if(line!=null){
                line.stop();
                line.close();
            }
            if(out!=null){
                try{
                    out.close();
                }catch(IOException e){
                    System.out.println("Error while closing output stream");
                }
            }
        }
    }
    
    public OutputStream getOutputStream(){
        return out;
    }
    
    public void stopRecord(){
        isRecording=false;
    }
    
    public byte[] getRecord(){
        if(out==null)
            return null;
        if(out instanceof ByteArrayOutputStream){
            byte[] record = ((ByteArrayOutputStream)out).toByteArray();
            System.out.println("Record size: "+record.length);
            return record;
        }
        return null;
    }
}
